<template>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto" style="max-width: 1000px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="BOM编号" prop="domCode">
            <el-input v-model="form.domCode" :disabled="form.isSystemCode" />
            <el-checkbox v-model="form.isSystemCode" @change="handleSystemCodeChange">系统编号</el-checkbox>
          </el-form-item>
          <el-form-item label="默认BOM">
            <el-checkbox v-model="form.domIsDel" />
          </el-form-item>
          <el-form-item label="成品类型" prop="domType">
            <el-select v-model="form.domType" placeholder="请选择成品类型">
              <el-option label="电子产品" value="electronic"></el-option>
              <el-option label="机械零件" value="mechanical"></el-option>
              <el-option label="化工产品" value="chemical"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日产量" prop="yieId">
            <el-input v-model.number="form.yieId" placeholder="请输入日产量" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="BOM主题" prop="domTopic">
            <el-input v-model="form.domTopic" placeholder="请输入BOM主题" />
          </el-form-item>
          <el-form-item label="版本" prop="domVersion">
            <el-input v-model="form.domVersion" placeholder="请输入版本" />
          </el-form-item>
          <el-form-item label="成品名称" prop="domName">
            <el-input v-model="form.domName" placeholder="请选择物品" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" @click="submitBomForm">提交</el-button>
        <el-button @click="resetForm">取消</el-button>
      </el-form-item>
      <el-divider />
      <div class="bom-accessories">
        <div style="margin-bottom: 10px;">
          <el-button type="primary" @click="addAccessory" :disabled="!isBasicInfoValid">新增行</el-button>
          <el-button type="danger" @click="removeAccessory" :disabled="!selectedAccessories.length">删除行</el-button>
        </div>
        <el-table :data="accessories" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="94"></el-table-column>
          <el-table-column label="序号" type="index" width="105"></el-table-column>
          <el-table-column label="物品编号" width="182">
            <template #default="scope">
              <el-input v-model="scope.row.code" size="default" placeholder="请输入物品编号" 
                :disabled="scope.row.isQueried && !scope.row.isEditing" />
            </template>
          </el-table-column>
          <el-table-column label="物品名称" width="182">
            <template #default="scope">
              <el-input v-model="scope.row.name" size="default" placeholder="请输入物品名称" 
                :disabled="scope.row.isQueried && !scope.row.isEditing" />
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="215">
            <template #default="scope">
              <el-input v-model="scope.row.model" size="default" placeholder="请输入规格型号" 
                :disabled="scope.row.isQueried && !scope.row.isEditing" />
            </template>
          </el-table-column>
          <el-table-column label="单位" width="116">
            <template #default="scope">
              <el-input v-model="scope.row.unit" size="default" placeholder="单位" 
                :disabled="scope.row.isQueried && !scope.row.isEditing" />
            </template>
          </el-table-column>
          <el-table-column label="品牌" width="160">
            <template #default="scope">
              <el-input v-model="scope.row.brand" size="default" placeholder="请输入品牌" 
                :disabled="scope.row.isQueried && !scope.row.isEditing" />
            </template>
          </el-table-column>
          <el-table-column label="配件数量" width="182">
            <template #default="scope">
              <el-input v-model="scope.row.quantity" size="default" placeholder="请输入数量" 
                :disabled="scope.row.isQueried && !scope.row.isEditing" />
            </template>
          </el-table-column>
          <el-table-column label="损耗率" width="182">
            <template #default="scope">
              <el-input v-model="scope.row.lossRate" size="default" placeholder="请输入损耗率"
                :disabled="scope.row.isQueried" />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作列" min-width="180">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleDelete(scope.row)">
                删除
              </el-button>
              <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
                {{ scope.row.isEditing ? '保存' : '修改' }}
              </el-button>
              <el-button v-if="scope.row.isEditing" link type="primary" size="small" @click="handleCancel(scope.row)">
                取消
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px; text-align: center;">
          <el-button type="success" @click="submitAccessories" :disabled="!accessories.length">提交BOM配件</el-button>
        </div>
      </div>
    </el-form>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref, watch, onMounted } from 'vue'
  import axios from 'axios'
  import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
  import { useRouter, useRoute } from 'vue-router'
  import {read,write} from "@/axios/axiosHelper"
  
  const router = useRouter()
  const route = useRoute()
  
  const domId = ref(localStorage.getItem('domId'));
  
  // BOM表单相关
  const formRef = ref<FormInstance | null>(null);
  const form = reactive({
    domId: 0,
    domCode: '',
    isSystemCode: false,
    domIsDel: false,
    domTopic: '',
    domType: '',
    domVersion: '',
    domName: '',
    yieId: 0,
    remark: ''
  });
  
  onMounted(async () => {
    if (domId.value) {
        try {
            // 获取 DOM 数据
            const domRes = await read.get(`/f-read/api/DOM/GetDOMId`, {
                params: {
                    domId: domId.value
                }
            })

            if (domRes.data.code === 200) {
                const data = domRes.data.data
                // 填充表单数据
                form.domId = data.domId
                form.domCode = data.domCode
                form.isSystemCode = data.isSystemCode
                form.domIsDel = data.domIsDel
                form.domTopic = data.domTopic
                form.domType = data.domType
                form.domVersion = data.domVersion
                form.domName = data.domName
                form.yieId = data.yieId
                form.remark = data.remark
                
                // 设置提交数据
                submittedData.value = data.domId
                
                // 获取配件数据
                await getDOMDetails()
            } else {
                ElMessage.error(domRes.data.msg || '获取DOM数据失败')
            }
        } catch (error: any) {
            console.error("获取DOM数据出错:", error)
            ElMessage.error('获取数据失败: ' + error.message)
        }
    }
  })
  
  const getDOMDetailsList = ref<any[]>([]);
  const getDOMDetails = async () => {
    try {
        const res = await read.get("/f-read/api/DOM/GetDOMDetails", {
            params: {
                domId: domId.value
            }
        })
        
        console.log("配件查询响应:", res) // 添加日志查看响应数据
        
        if (res.data.code === 200) {
            // 确保数据存在且是数组
            if (Array.isArray(res.data.data)) {
                getDOMDetailsList.value = res.data.data
                
                // 更新配件列表
                accessories.value = res.data.data.map(item => ({
                    domId: domId.value,
                    domDetailsId: item.domDetailsId,
                    code: item.code || '',
                    name: item.name || '',
                    model: item.model || '',
                    unit: item.unit || '',
                    brand: item.brand || '',
                    quantity: item.quantity || '',
                    lossRate: item.lossRate || '',
                    isQueried: true,
                    isEditing: false
                }))
                
                console.log("更新后的配件列表:", accessories.value) // 添加日志查看更新后的数据
            } else {
                console.warn("配件数据格式不正确:", res.data.data)
                ElMessage.warning('配件数据格式不正确')
            }
        } else {
            ElMessage.error(res.data.msg || '获取配件数据失败')
        }
    } catch (error: any) {
        console.error("获取配件数据出错:", error)
        ElMessage.error('获取配件数据失败: ' + error.message)
    }
  }
  
  const rules = reactive({
    domCode: [
      { required: true, message: 'BOM编号不能为空', trigger: 'blur' },
      { min: 5, message: '编号长度不能少于5个字符', trigger: 'blur' }
    ],
    domType: [
      { required: true, message: '请选择成品类型', trigger: 'change' }
    ],
    yieId: [
      { required: true, message: '请输入日产量', trigger: 'blur' },
      { type: 'number', message: '日产量必须为数字', trigger: 'blur' }
    ],
    domTopic: [
      { required: true, message: 'BOM主题不能为空', trigger: 'blur' }
    ],
    domVersion: [
      { required: true, message: '版本不能为空', trigger: 'blur' }
    ],
    domName: [
      { required: true, message: '成品名称不能为空', trigger: 'blur' }
    ]
  });
  
  // 配件数据
  interface Accessory {
    domId: number;
    domDetailsId?: number;
    code: string;
    name: string;
    model: string;
    unit: string;
    brand: string;
    quantity: string;
    lossRate: string;
    isQueried?: boolean;
    isEditing?: boolean;
  }
  
  const accessories = ref<Accessory[]>([]);
  const selectedAccessories = ref<Accessory[]>([]);
  
  // 选择行
  const handleSelectionChange = (val: Accessory[]) => {
    selectedAccessories.value = val;
  }
  
  // 检查基本信息是否有效
  const isBasicInfoValid = ref(false);
  
  // 基本信息是否已提交
  const submittedData = ref<any>(null);
  
  // 监听表单变化
  watch(() => form, (newForm) => {
    // 检查必填字段是否都已填写
    isBasicInfoValid.value = !!(
      newForm.domCode &&
      newForm.domType &&
      newForm.domTopic &&
      newForm.domVersion &&
      newForm.domName &&
      newForm.yieId > 0
    );
  }, { deep: true });
  
  // 添加配件
  const addAccessory = () => {
    if (!isBasicInfoValid.value) {
      ElMessage.warning('请先完善基本信息');
      return;
    }
    if (!submittedData.value) {
      ElMessage.warning('请先提交基本信息');
      return;
    }
    accessories.value.push({
      domId: submittedData.value,
      domDetailsId: undefined,
      code: '', name: '', model: '', unit: '', brand: '', quantity: '', lossRate: '', isQueried: false, isEditing: false
    });
  };
  
  // 移除配件
  const removeAccessory = () => {
    // 检查选中的行是否包含查询出的数据
    const hasQueriedData = selectedAccessories.value.some(item => item.isQueried);
  
    if (hasQueriedData) {
      ElMessage.warning('当前不能删除，所选行有数据');
      return;
    }
  
    accessories.value = accessories.value.filter(item => !selectedAccessories.value.includes(item));
    selectedAccessories.value = [];
  }
  
  // 生成BOM编号
  const generatedomCode = () => {
    const timestamp = new Date().getTime().toString().slice(-6);
    const randomStr = Math.random().toString(36).slice(2, 5).toUpperCase();
  
    let prefix = 'BOM';
    if (form.domType === 'electronic') prefix = 'ELC';
    if (form.domType === 'mechanical') prefix = 'MEC';
    if (form.domType === 'chemical') prefix = 'CHE';
  
    return `${prefix}-${timestamp}-${randomStr}`;
  };
  
  // 处理系统编号勾选变化
  const handleSystemCodeChange = (checked: boolean) => {
    if (checked) {
      // 检查是否已选择成品类型
      if (!form.domType) {
        ElMessage.warning('请先选择成品类型再生成系统编号');
        form.isSystemCode = false;
        return;
      }
  
      form.domCode = generatedomCode();
    } else {
      form.domCode = '';
    }
  };
  
  // 监听成品类型变化，更新编号前缀
  watch(() => form.domType, (newVal) => {
    if (form.isSystemCode && form.domCode) {
      // 如果已生成编号且修改了类型，重新生成
      form.domCode = generatedomCode();
    }
  });
  
  // 提交BOM表单
  const submitBomForm = () => {
    // 系统编号模式下自动生成
    if (form.isSystemCode && !form.domCode) {
      form.domCode = generatedomCode();
    }
  
    if (formRef.value) {
      formRef.value.validate((valid: boolean) => {
        if (valid) {
          const payload = {
            ...form,
            accessories: accessories.value
          }
          write.post('/f-write/api/DOM/AddDOM', payload)
            .then(res => {
              if (res.data.code === 200) {
                ElMessage.success(res.data.msg);
                // 保存返回的数据
                submittedData.value = res.data.data;
                console.log('提交成功，返回数据：', submittedData.value);
                // 清空配件列表，因为基本信息已更新
                accessories.value = [];
                selectedAccessories.value = [];
              } else {
                ElMessage.error(res.data.msg);
              }
            })
            .catch(error => {
              ElMessage.error('提交失败:' + error.message);
              console.error(error);
            });
        } else {
          ElMessage.warning('请完善表单信息');
        }
      });
    }
  };
  
  // 重置BOM表单
  const resetForm = () => {
    // 清空返回数据
    submittedData.value = null;
    // 重置表单数据
    form.domId = 0;
    form.domCode = '';
    form.isSystemCode = false;
    form.domIsDel = false;
    form.domTopic = '';
    form.domType = '';
    form.domVersion = '';
    form.domName = '';
    form.yieId = 0;
    form.remark = '';
    // 清空配件列表
    accessories.value = [];
    selectedAccessories.value = [];
  };
  
  // 提交BOM配件
  const submitAccessories = async () => {
    if (!isBasicInfoValid.value) {
      ElMessage.warning('请先完善基本信息');
      return;
    }
  
    if (!accessories.value.length) {
      ElMessage.warning('请先添加配件信息');
      return;
    }
  
    // 验证配件数据
    const invalidAccessories = accessories.value.filter(item =>
      !item.code || !item.name || !item.model || !item.unit || !item.brand || !item.quantity
    );
  
    if (invalidAccessories.length > 0) {
      ElMessage.warning('请完善所有配件信息');
      return;
    }
  
    // 构建批量提交的数据
    const batchData = accessories.value.map(item => ({
      domId: submittedData.value,
      domDetailsId: item.domDetailsId,
      code: item.code,
      name: item.name,
      model: item.model,
      unit: item.unit,
      brand: item.brand,
      quantity: item.quantity,
      lossRate: item.lossRate
    }));
  
    console.log("配件数据：", batchData);
  
    try {
      // 循环添加每个配件
      for (let i = 0; i < batchData.length; i++) {
        const item = batchData[i];
        console.log(`正在添加第 ${i + 1}/${batchData.length} 个配件:`, item);
  
        const res = await write.post("/f-write/api/DOMDetails/AddDOMDetails", item);
  
        if (res.data.code === 200) {
          console.log(`第 ${i + 1} 个配件添加成功`);
        } else {
          throw new Error(`第 ${i + 1} 个配件添加失败: ${res.data.msg}`);
        }
      }
  
      // 所有配件添加成功
      ElMessage.success('所有配件添加成功');
      // 清空配件列表
      accessories.value = [];
      selectedAccessories.value = [];
  
      // 重新获取配件列表数据
      await getDOMDetails();
  
    } catch (error: any) {
      ElMessage.error('添加失败: ' + error.message);
      console.error('添加失败:', error);
    }
  };
  
  // 修改处理函数
  const handleEdit = async (row: Accessory) => {
    if (row.isEditing) {
      // 如果当前是编辑状态，则保存
      try {
        const res = await write.post("/f-write/api/DOMDetails/UpdateDOMDetails", {
          domDetailsId: row.domDetailsId,
          domId: row.domId,
          code: row.code,
          name: row.name,
          model: row.model,
          unit: row.unit,
          brand: row.brand,
          quantity: row.quantity,
          lossRate: row.lossRate
        });

        if (res.data.code === 200) {
          ElMessage.success('保存成功');
          row.isEditing = false;
          // 重新获取配件列表
          await getDOMDetails();
        } else {
          ElMessage.error(res.data.msg || '保存失败');
        }
      } catch (error: any) {
        ElMessage.error('保存失败: ' + error.message);
      }
    } else {
      // 如果当前不是编辑状态，则进入编辑状态
      // 将其他行的编辑状态设为 false
      accessories.value.forEach(item => {
        if (item !== row) {
          item.isEditing = false;
        }
      });
      row.isEditing = true;
    }
  };
  
  // 取消编辑
  const handleCancel = async (row: Accessory) => {
    // 取消编辑，重新获取数据
    await getDOMDetails();
    row.isEditing = false;
  };
  
  // 删除处理函数
  const handleDelete = (row: Accessory) => {
    ElMessageBox.confirm(
      '确定要删除这个配件吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(async () => {
        try {
          // 调用删除API
          const res = await write.post(`/f-write/api/DOMDetails/DeleteDOMDetails`, {
            domDetailsId: row.domDetailsId
          });
          if (res.data.code === 200) {
            ElMessage.success('删除成功');
            // 重新获取配件列表
            await getDOMDetails();
          } else {
            ElMessage.error(res.data.msg || '删除失败');
          }
        } catch (error: any) {
          ElMessage.error('删除失败: ' + error.message);
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
  };
  
  // Add this new function
  const handleModify = (domId: number) => {
    router.push({
        path: '/update-dom',
        query: { domId: domId }
    })
  }

  // 确保 watch 正确监听 getDOMDetailsList 的变化
  watch(getDOMDetailsList, (newValue) => {
    console.log("getDOMDetailsList 发生变化:", newValue) // 添加日志
    if (newValue && newValue.length > 0 && submittedData.value) {
        accessories.value = newValue.map(item => ({
            domId: submittedData.value,
            domDetailsId: item.domDetailsId,
            code: item.code || '',
            name: item.name || '',
            model: item.model || '',
            unit: item.unit || '',
            brand: item.brand || '',
            quantity: item.quantity || '',
            lossRate: item.lossRate || '',
            isQueried: true,
            isEditing: false
        }))
        console.log("watch 更新后的配件列表:", accessories.value) // 添加日志
    }
  }, { deep: true })
  </script>
  
  <style scoped>
  .bom-accessories {
    margin-top: 20px;
  }
  </style>